package com.test.mywebtest.controller;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;


/**
 * 获取word文档中的文本内容
 *
 */
@RestController
@RequestMapping("/test")
public class WordController {

    @PostMapping("/test")
    public String test(@RequestParam(name = "file") MultipartFile multipartFile) {
        String path = multipartFile.getOriginalFilename();
        String buffer = "";
        try {
            if (path.endsWith(".doc")) {
                InputStream is = multipartFile.getInputStream();
                WordExtractor extractor = new WordExtractor(is);
                buffer = extractor.getText().toString();
                is.close();
            } else if (path.endsWith("docx")) {
                InputStream is = multipartFile.getInputStream();
                XWPFDocument ex = new XWPFDocument(is);
                XWPFWordExtractor exx = new XWPFWordExtractor(ex);
                buffer = exx.getText();
                exx.close();
                is.close();
            } else {
                return null;
            }
            System.out.println(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
